package com.gome.boot.config.elasticsearch.cluster;

import com.gome.boot.common.util.StringToUtils;
import com.gome.boot.config.elasticsearch.BaseElasticsearchConfig;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * ES服务基础配置.
 * <br/>多集群模式.
 *
 * @author baoxiufeng
 */
public abstract class BaseMultiClusterElasticsearchConfig extends BaseElasticsearchConfig {

    @Bean(name = "multiClient")
    @ConditionalOnMissingBean
    public MultiClusterClient multiClient() throws Exception {
        List<String> clusterNames = StringToUtils.stringToList(env.getRequiredProperty(KEY_ES_CLUSTER_NAME));
        List<String> clusterNodes = StringToUtils.stringToList(env.getRequiredProperty(KEY_ES_CLUSTER_NOES), ";");
        if (clusterNames.size() != clusterNodes.size()) {
            throw new RuntimeException("[BaseMultiClusterElasticsearchConfig] cluster count is not same to nodes count.");
        }
        if (new HashSet<String>(clusterNames).size() < clusterNames.size()) {
            throw new RuntimeException("[BaseMultiClusterElasticsearchConfig] cluster name must not be same in multi cluster mode.");
        }
        MultiClusterClient multiClient = MultiClusterClient.getInstance();
        Iterator<String> nameIter = clusterNames.iterator();
        Iterator<String> nodeIter = clusterNodes.iterator();
        String name = null;
        while (nameIter.hasNext()) {
            name = nameIter.next();
            multiClient.addClient(name, createClient(name, nodeIter.next()));
        }
        multiClient.setClusterSelector(multiClusterSelector());
        multiClient.setMultiple(multiClient.getClientMap().size() > 1);
        return multiClient;
    }

    @Bean(name = "clusterClient")
    @ConditionalOnMissingBean
    public ClusterClient clusterClient(@Qualifier("multiClient") MultiClusterClient multiClient) {
        return multiClient.selectClient();
    }

    @Bean
    @ConditionalOnMissingBean
    public Client client(@Qualifier("clusterClient") ClusterClient clusterClient) {
        return clusterClient.getClient();
    }

    @Bean
    @ConditionalOnMissingBean
    public ElasticsearchTemplate elasticsearchTemplate(@Qualifier("clusterClient") ClusterClient clusterClient) {
        return clusterClient.getTemplate();
    }

    /**
     * 多集群选择器.
     * <br/>多个集群时，应用可设置集群选择器.
     *
     * @return 集群选择器
     */
    protected MultiClusterSelector multiClusterSelector() {
        return null;
    }
}
